import { createAsyncThunk, createSlice, } from '@reduxjs/toolkit'
import { namePswloginAPI, type NamePswParams, type LoginData } from '../../api/login'
import { getUserInfoAPI, type ResponseUserInfo } from '../../api/user';


//用户切片
export interface userState {
    isLogin: boolean,
    userInfo: {
        uid: string,
        nickname: string,
        avatar: string,
        username: string
    },
    token: string,
    loading: boolean; // 新增：登录请求中的加载状态
    error: string | null; // 新增：登录失败的错误信息
}
const userInfoLocal = localStorage.getItem('userInfo')
const initialState: userState = {
    isLogin: !!localStorage.getItem('token'),
    userInfo: userInfoLocal ? JSON.parse(userInfoLocal) : {
        uid: localStorage.getItem('uid') || '',
        nickname: '',
        avatar: '',
        username: ''
    },
    token: localStorage.getItem('token') || '',
    loading: false,
    error: null
}

export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        clearErr:(state)=>{
              state.error=null
        },
        clearLogOut: (state) => {
            state.userInfo = {
                uid: '',
                nickname: '',
                avatar: '',
                username: ''
            }
            state.token = ''
            state.isLogin = false
            localStorage.removeItem('token')
            localStorage.removeItem('uid')
            localStorage.removeItem('userInfo')
        }
    }, extraReducers: (builder) => {
        builder
            .addCase(namePswlogin.pending, (state) => {
                state.loading = false;
                state.error = null
            })
            .addCase(namePswlogin.fulfilled, (state, action) => {
                state.isLogin = true;
                state.token = action.payload.newToken.token
                localStorage.setItem('token', action.payload.newToken.token)
                state.userInfo.uid = action.payload.uid
                localStorage.setItem('uid', action.payload.uid)
            })
            .addCase(namePswlogin.rejected, (state, action) => {
                state.isLogin = false;
                state.loading = false;
                state.error = action.payload || '登录失败'

            });
        builder.addCase(getUserInfo.pending, (state) => {
            state.error = null
        })
            .addCase(getUserInfo.fulfilled, (state, action) => {
                state.userInfo.avatar = action.payload.avatar_file.url
                state.userInfo.nickname = action.payload.nickname
                state.userInfo.username = action.payload.username
                state.userInfo.uid = action.payload._id
                localStorage.setItem('userInfo', JSON.stringify(state.userInfo))
            })
            .addCase(getUserInfo.rejected, (state, action) => {
                state.error = action.payload || '获取用户信息失败'
                state.token = ''
                state.isLogin = false
                localStorage.removeItem('token')
                localStorage.removeItem('uid')
                localStorage.removeItem('userInfo')
            })
    },
})


export const {clearErr, clearLogOut } = userSlice.actions

export const userReducer = userSlice.reducer


export const namePswlogin = createAsyncThunk<LoginData, NamePswParams, {
    rejectValue: string; // 失败时返回的错误信息类型
}>("user/login", async (data: NamePswParams, { rejectWithValue }) => {
    try {
        const res = await namePswloginAPI(data)
        console.log(res)
        if (res.status !== 200) {
            return rejectWithValue('拒绝访问')
        }
        if (res.data.errCode !== 0) {
            return rejectWithValue('登录失败')
        }
        return res.data
    } catch (error) {
        console.log(error)
        return rejectWithValue("登录失败，请重试");
    }

})

export const getUserInfo = createAsyncThunk<ResponseUserInfo, void, {
    rejectValue: string; // 失败时返回的错误信息类型
}>("user/getUserInfo", async (_, { rejectWithValue }) => {
    try {
        const res = await getUserInfoAPI()
        console.log(res)
        if (res.data.code !== 0) {
            return rejectWithValue(res.data.msg)
        }
        return res.data.data
    } catch (error) {
        console.log(error)
        return rejectWithValue(error+'');
    }

})